<template>
	<view class="content">
		<textarea v-model="textToEncode" @input="generateQRCode" maxlength="-1" auto-height placeholder="输入要编码的文字"></textarea>
		<view class="uni-flex uni-row">
			<view class="uni-flex uni-column"
				style="-webkit-flex: 1;flex: 1;-webkit-justify-content: space-between;justify-content: space-between;">
				<view @click="chooseLogo">+ 请选择logo图片</view>
				<textarea @input="urlLogo" inputmode="url" placeholder="请输入logo网址"
					style="width:200px;height: 80px;"></textarea>
			</view>
			<view class="text uni-flex"
				style="width: 200rpx;height: 220rpx;-webkit-justify-content: center;justify-content: center;-webkit-align-items: center;align-items: center;">
				<image :src="logoUrl" mode="widthFix" style="width:80px"></image>
			</view>
		</view>
		<button @click="generateQRCode" size="mini">生成二维码</button>
		<canvas id="qrcode-canvas" style="display: none;"></canvas>
		<image :src="qrcodeImage" mode="widthFix" style="width: 200px;height: 200px;"></image>
		<view class="uni-flex uni-row">
			<view class="uni-flex uni-column"
				style="-webkit-flex: 1;flex: 1;-webkit-justify-content: space-between;justify-content: space-between;">
				<view @click="chooseQrcode">+ 请选择二维码图片</view>
				<textarea @input="urlQrcode" inputmode="url" placeholder="请输入二维码网址"
					style="width:200px;height: 80px;"></textarea>
			</view>
			<view class="text uni-flex"
				style="width: 200rpx;height: 220rpx;-webkit-justify-content: center;justify-content: center;-webkit-align-items: center;align-items: center;">
				<image :src="imageUrl" mode="widthFix" style="width:80px"></image>
			</view>
		</view>
		<button @click="decodeQRCode" size="mini">解析二维码</button>
		<text @click="copyResult">{{ decodedText }}</text>
	</view>
</template>

<script>
	import QRCode from 'qrcodejs2';
	import decode from 'jsqr';


	export default {
		data() {
			return {
				textToEncode: '',
				imageUrl: '',
				qrcodeImage: '',
				decodedText: '',
				logoUrl: ''
			};
		},
		onReady() {
			console.log('QRCode ready = ' + !!QRCode);
			console.log('decode ready = ' + !!decode);
		},
		methods: {
			generateQRCode() {
				const canvas = document.getElementById('qrcode-canvas');
				canvas.innerHTML = '';
				this.qrcodeImage = '';
				if (!this.textToEncode) return;
				const qrcode = new QRCode(canvas, {
					text: this.textToEncode,
					width: 200,
					height: 200,
					colorDark: '#000000',
					colorLight: '#ffffff',
					correctLevel: QRCode.CorrectLevel.H
				});

				if (this.logoUrl) {
					this.addLogoToQRCode(qrcode);
				}

				// 将 canvas 转换为 base64 图片
				this.qrcodeImage = canvas.firstElementChild.toDataURL('image/png');
			},
			addLogoToQRCode(qrcode) {
				const self = this;
				const logoImg = new Image();
				logoImg.src = this.logoUrl;
				logoImg.onload = () => {
					const canvas = qrcode._oDrawing;
					const ctx = canvas._oContext;
					const logoSize = 80;
					const x = (canvas._elCanvas.width - logoSize) / 2;
					const y = (canvas._elCanvas.height - logoSize) / 2;

					ctx.drawImage(logoImg, x, y, logoSize, logoSize);

					self.qrcodeImage = canvas._elCanvas.toDataURL('image/png');
				};
			},
			chooseLogo() {
				const self = this;
				uni.chooseImage({
					count: 1,
					sourceType: ['album'], //从相册选择
					success: function(res) {
						const file = res.tempFiles[0];
						if (file) {
							const reader = new FileReader();
							reader.onloadend = () => {
								self.logoUrl = reader.result;
								self.generateQRCode();
							};
							reader.readAsDataURL(file);
						}
					}
				})
			},
			chooseQrcode() {
				const self = this;
				uni.chooseImage({
					count: 1,
					sourceType: ['album'], //从相册选择
					success: function(res) {
						const file = res.tempFiles[0];
						if (file) {
							const reader = new FileReader();
							reader.onloadend = () => {
								self.imageUrl = reader.result;
								self.decodeQRCode();
							};
							reader.readAsDataURL(file);
						}
					}
				})
			},
			urlLogo(e) {
				const url = e.detail.value;
				if (!url) {
					if (this.logoUrl.startsWith('http')) {
						this.logoUrl = '';
					}
				} else {
					if (url.startsWith('http')) {
						this.logoUrl = url;
					}
				}
				this.generateQRCode();
			},
			urlQrcode(e) {
				const url = e.detail.value;
				if (!url) {
					if (this.imageUrl.startsWith('http')) {
						this.imageUrl = '';
					}
				} else {
					if (url.startsWith('http')) {
						this.imageUrl = url;
					}
				}
				this.decodeQRCode();
			},
			async decodeQRCode() {
				this.decodedText = '';
				if (!this.imageUrl) return;
				const img = document.createElement('img');
				if (this.imageUrl.startsWith('http')) {
					const response = await fetch(this.imageUrl);
					const blob = await response.blob();
					img.src = URL.createObjectURL(blob);
				} else {
					img.src = this.imageUrl;
				}
				img.onload = () => {
					const canvas = document.createElement('canvas');
					canvas.width = img.width;
					canvas.height = img.height;
					const ctx = canvas.getContext('2d');
					ctx.drawImage(img, 0, 0);
					const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
					const code = decode(imageData.data, imageData.width, imageData.height);
					if (code) {
						this.decodedText = code.data;
					} else {
						this.decodedText = '无法解析二维码';
					}
				};
			},
			copyResult: function() {
				uni.setClipboardData({
					data: this.decodedText
				});
			}
		}
	};
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 10px;
	}
</style>